import com.google.gson.Gson;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;

public class ListBook extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setContentType("application/json;charset=UTF-8");

        PrintWriter out = response.getWriter();
        List<Map<String, String>> bookList = new ArrayList<>();

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/linux_exam?useUnicode=true&characterEncoding=UTF-8",
                "root", "1qaz@WSX#EDC");

            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM t_book");

            while (rs.next()) {
                Map<String, String> book = new HashMap<>();
                book.put("number", rs.getString("number"));
                book.put("name", rs.getString("name"));
                book.put("author", rs.getString("author"));
                bookList.add(book);
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            Map<String, String> err = new HashMap<>();
            err.put("error", e.getMessage());
            bookList.add(err);
        }

        out.print(new Gson().toJson(bookList));
    }
}

